/**
 * 
 * @author  phoenics@126.com
 * @version v.0.1
 * @date  2018年3月15日 上午9:09:15 
 * 
 */
package phoenics.upservice.restcontroller;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import phoenics.common.BaseData.RestResp;
import phoenics.upservice.dto.UserUpdata;
import phoenics.upservice.entity.User;
import phoenics.upservice.repository.UserRepo;

/**
 *
 */
@RestController  
@RequestMapping("/register")
public class UserController {
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(UserController.class);

	 @Resource  
	    private UserRepo userRepo;  
	 @Autowired
	 BCryptPasswordEncoder passwordEncoder;
	  
	    @PostMapping("/register")  
	    public RestResp register(@RequestBody UserUpdata restUser){  
	        return userRepo.findByMobile(restUser.getMobile()).map(u -> RestResp.fail("手机号码已经存在")).orElseGet(() -> {
	        	User user=new User();
	        	user.setMobile(restUser.getMobile());
	        	user.setPassword(passwordEncoder.encode(restUser.getPassword()));
	           User u = userRepo.save(user);  
	           logger.info("{} registered", u);  
	           return RestResp.success("注册成功");  
	        });  
	    }  
	    @PostMapping("/forget")  
	    public RestResp forget(@RequestBody UserUpdata user){  
	        return userRepo.findMobileCached(user.getMobile()).map(u -> {
	        	u.setPassword(passwordEncoder.encode(user.getPassword()));
	        	userRepo.save(u);
	        	return RestResp.success("密码修改成功");  
	        }).orElse(RestResp.fail("手机未注册")
	        );  
	    } 
}
